package cn.edu.hit.education.listener;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import cn.edu.hit.education.model.CourseNode;
import cn.edu.hit.education.model.Node;
import educationschedule.Activator;

public class CourseDragSourceListener extends DragSourceAdapter {
	private TreeViewer treeViewer;

	/**
	 * @param parentComposite
	 *            - the composite that holds all pictures
	 * @param source
	 *            - the drag source
	 *
	 */
	public CourseDragSourceListener(TreeViewer treeViewer) {
		this.treeViewer = treeViewer;
	}

	@Override
	public void dragStart(DragSourceEvent dragSourceEvent) {
		// getting control widget - Label in this case
		/*
		 * Label label = ((Label) ((DragSource)
		 * dragSourceEvent.getSource()).getControl()); // make the drag icon the
		 * dragged image itself dragSourceEvent.image = label.getImage();
		 */

		// add shadow to drag icon
		dragSourceEvent.image = AbstractUIPlugin.imageDescriptorFromPlugin(
				Activator.PLUGIN_ID, "icons/course.png").createImage();
	}

	/**
	 * The method computes the position / index of the source control (label) in
	 * the children array of the parent composite. This index is passed to the
	 * drop target using the data field of the drag source event.
	 */
	@Override
	public void dragSetData(DragSourceEvent event) {
		// event.data = "Test Text";
		/*
		 * for (int i = 0; i < parentComposite.getChildren().length; i++) { if
		 * (parentComposite.getChildren()[i].equals(source.getControl())) {
		 * event.data = new Integer(i).toString(); break; } }
		 */
		Node node = (Node) ((IStructuredSelection) treeViewer.getSelection())
				.getFirstElement();
		if (node instanceof CourseNode) {
			CourseNode cNode = (CourseNode)node;
			event.data = String.valueOf(cNode.getId());
			event.doit = true;
		} else {
			event.data = "-1";
			event.doit = true;
		}

	}
}
